﻿// MIT License
//
// Copyright (c) 2021-present zuohuaijun, Daming Co.,Ltd and Contributors
//
// 电话/微信：18020030720 QQ群1：87333204 QQ群2：252381476

using Admin.NET.Application.Const;
using Admin.Net.InformationPlatform.Entity;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Mvc;
using Nest;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Admin.Net.InformationPlatform.Entity.Equipment;
using Admin.Net.InformationPlatform.Service.Equipment.Dto;
using Admin.Net.InformationPlatform.Entity.ProdectFile;
using Admin.NET.Core;
using Furion.FriendlyException;
using MathNet.Numerics.Distributions;

namespace Admin.Net.InformationPlatform.Service.Equipment;

/// <summary>
/// 华为验厂-设备管理系统
/// </summary>
[ApiDescriptionSettings(groups: "HWYC", Name = "设备管理系统", Tag = "设备管理", Order = 200)]
public class EqipmentService : IDynamicApiController, ITransient
{
    /// <summary>
    /// 单例数据链接
    /// </summary>
    ISqlSugarClient db;
    /// <summary>
    /// T100数据库
    /// </summary>
    private SqlSugarProvider _T100Db;
    private SqlSugarProvider _SjDb;
    private SqlSugarProvider _plm;
    private SqlSugarProvider _Dilon;


    /// <summary>
    /// 用户信息
    /// </summary>
    TokenUser _User;
    /// <summary>
    /// SOP工程文件管理
    /// </summary>
    /// <param name="db"></param>
    public EqipmentService(ISqlSugarClient db)
    {
        this.db = db;
        this._T100Db = this.db.AsTenant().GetConnection(T100TestArea.ConfigId);
        this._SjDb = this.db.AsTenant().GetConnection(SJDB.ConfigId);
        this._plm = this.db.AsTenant().GetConnection(PLM.ConfigId);
        this._Dilon = this.db.AsTenant().GetConnection(Dilon.ConfigId);
        // 获取 `Jwt` 存储的信息 企业编号与据点信息
        _User = Util.SjCommonUtil.GetT100UserTokenInfo(_T100Db, _Dilon);

    }

    /// <summary>
    /// 查询设备详细信息
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost("/HWYC/SelectEquipmentBasicInformationList")]
    public async   Task<SqlSugarPagedList<HWEquipmentBasicInformationOut>> SelectEquipmentBasicInformation(SelectEquipmentBasicInput input) {



            var output = await _SjDb.Queryable<HWEquipmentBasicInformation>()
            .Where(l => l.LIFECYCLE == 0)
            .WhereIF(!string.IsNullOrEmpty(input.DEVICENUMBER), (l) => (l.DEVICENUMBER ==input.DEVICENUMBER))//设备编号
            .OrderBy(l => l.CREATETIME, OrderByType.Desc) //创建日期排序
            .Select(l => new HWEquipmentBasicInformationOut
            {
                BID = l.BID,
                EQUIPMENTTYPENO = l.EQUIPMENTTYPENO,
                DEVICENUMBER = l.DEVICENUMBER,
                EQUIPMENTSTATE = l.EQUIPMENTSTATE,
                CREATETIME = l.CREATETIME,
                MAINTENANCEINTERVALS = l.MAINTENANCEINTERVALS,
                LIFECYCLE = l.LIFECYCLE

            }).ToPagedListAsync(input.Page, input.PageSize);


        List<HWEquipmentBasicInformationOut> listOut = (List<HWEquipmentBasicInformationOut>)output.Items;
        if (listOut.Count ==0) {
            throw Oops.Oh($"未查询到数据！");

        }
        HashSet<string> strings = new HashSet<string>();

        foreach (HWEquipmentBasicInformationOut item in listOut)
        {
            strings.Add(item.DEVICENUMBER);
        }


        var outputZi =   _SjDb.Queryable<HWEquipmentBasicZi>().Where(it => strings.Contains(it.DEVICENUMBER))
            
            .ToList();


        for (int i = 0; i < listOut.Count; i++)
        {
            listOut[i].MATERIALNO = new List<MaterialnoMessage>();
            foreach (HWEquipmentBasicZi item in outputZi)
            {              
                if (listOut[i].DEVICENUMBER.Equals(item.DEVICENUMBER)) {

                    listOut[i].MATERIALNO.Add(new MaterialnoMessage() {

                        MATERIALNO = item.MATERIALNO,
                        ITEMNAME = item.ITEMNAME,
                        EQUIPMENTSPECS = item.EQUIPMENTSPECS,
                        DEVICENUMBER = item.DEVICENUMBER,

                    });
                }

            }

        }
        output.Items = listOut;

/*
        var outputZi = await _SjDb.Queryable<HWEquipmentBasicZi>()
           .WhereIF(!string.IsNullOrEmpty(input.DEVICENUMBER), (l) => (l.DEVICENUMBER == input.DEVICENUMBER))//设备编号
           .OrderBy(l => l.CREATETIME, OrderByType.Desc) //创建日期排序
           .Select(l => new HWEquipmentBasicZi
           {
               BID = l.BID,
               MATERIALNO = l.MATERIALNO,
               DEVICENUMBER = l.DEVICENUMBER,
               CREATETIME = l.CREATETIME,
               ITEMNAME = l.ITEMNAME,
               EQUIPMENTSPECS = l.EQUIPMENTSPECS,


           }).ToPagedListAsync(input.Page, input.PageSize);



        List<HWEquipmentBasicZi> list = (List<HWEquipmentBasicZi>)outputZi.Items;*/



        /* HashSet<string> stringSet = new HashSet<string>();
         foreach (HWEquipmentBasicInformationOut item in listOut) {
             stringSet.Add(item.DEVICENUMBER);
         }

         Dictionary<string, List<MaterialnoMessage>> keyValues = new Dictionary<string, List<MaterialnoMessage>>();
         List<MaterialnoMessage> messages = new List<MaterialnoMessage>();  
         if (list.Count!=0) {

             foreach (HWEquipmentBasicZi item in list)
             {
                 MaterialnoMessage message = new MaterialnoMessage() {

                 MATERIALNO = item.MATERIALNO,
                 ITEMNAME = item.ITEMNAME,
                 EQUIPMENTSPECS = item.EQUIPMENTSPECS,
                 DEVICENUMBER = item.DEVICENUMBER,
                 };
                 messages.Add(message);
             }
         }


         if (listOut.Count!=0) {

             foreach (MaterialnoMessage item in messages)
             {
                 if (stringSet.Contains(item.DEVICENUMBER)) { 

                 }

             }


             listOut[0].MATERIALNO = messages;
         }*/


        return output;

    }

    /// <summary>
    /// 添加设备信息
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost("/HWYC/SaveEquipmentBasicInformation")]
    public async Task<string> SaveEquipmentBasicInformation([FromBody] List<EquipmentBasicInformationInput> input)
    {
        List<HWEquipmentBasicInformation> list = new List<HWEquipmentBasicInformation>();
        List<HWEquipmentBasicZi> Zilist = new List<HWEquipmentBasicZi>();
        if (input.Count() > 0)
        {
            DateTime creteTime = DateTime.Now;

            for (int i = 0; i < input.Count(); i++)
            {

                if (string.IsNullOrEmpty(input[i].DEVICENUMBER) || input[i].MATERIALNO.Count==0  || string.IsNullOrEmpty(input[i].EQUIPMENTTYPENO) || string.IsNullOrEmpty(input[i].DEVICENUMBER))
                {
                    throw Oops.Oh($"请填写完整参数！");

                }

                //判断单据存在
                int cnt = await _SjDb.Queryable<HWEquipmentBasicInformation>()
                    .Where(a=> a.DEVICENUMBER == input[i].DEVICENUMBER)
                     .Where(l => l.LIFECYCLE == 0)
                    .Select(a => a.BID)
                    .CountAsync();
                if (cnt > 0)
                {
                    throw Oops.Oh($"任务已经存在！");
                }
            //    StringBuilder sb = new StringBuilder();

               
               
                for (int j = 0; j < input[i].MATERIALNO.Count; j++)
                {
                    HWEquipmentBasicZi basicZi = new HWEquipmentBasicZi();
                    basicZi.MATERIALNO = input[i].MATERIALNO[j].MATERIALNO;
                    basicZi.ITEMNAME = input[i].MATERIALNO[j].ITEMNAME;
                    basicZi.DEVICENUMBER = input[i].DEVICENUMBER;
                    basicZi.EQUIPMENTSPECS = input[i].MATERIALNO[j].EQUIPMENTSPECS;
                    basicZi.CREATETIME = creteTime;
                    Zilist.Add(basicZi);
                }

                            
                    var details = new HWEquipmentBasicInformation
                    {
                        EQUIPMENTTYPENO = input[i].EQUIPMENTTYPENO,
                        DEVICENUMBER = input[i].DEVICENUMBER,
                        EQUIPMENTSTATE = input[i].EQUIPMENTSTATE,
                        LIFECYCLE = 0,
                        CREATETIME = creteTime,
                        MAINTENANCEINTERVALS = input[i].MAINTENANCEINTERVALS,

                    };
                    list.Add(details);

            }
        }
        #region 插入事务
        try
        {
            //开启事务
            _SjDb.Ado.BeginTran();
            int cnt = await _SjDb.Insertable<HWEquipmentBasicInformation>(list).ExecuteCommandAsync();
            int cnt2 = await _SjDb.Insertable<HWEquipmentBasicZi>(Zilist).ExecuteCommandAsync();

            if (cnt == 0 || cnt2 ==0)
            {
                throw Oops.Oh($"新建任务失败！");
            }
            //提交事务
            _SjDb.Ado.CommitTran();
            return "插入成功";
        }
        catch (Exception e)
        {
            //回滚事务
            _SjDb.Ado.RollbackTran();
            throw Oops.Oh($"异常：{e.Message}");
        }
        #endregion

    }

    /// <summary>
    /// 删除订单
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost("/HWYC/DeleteEquipmentBasicInformation")]
    public async Task<string> DeleteEquipmentBasicInformation(DeleteEquipmentInput input) {

        //判断单据存在

 /*       int selectCount = _SjDb.Queryable<HWEquipmentBasicInformation>()
            .Where(a => a.BID == input.BID)
            .Count();*/

        List<HWEquipmentBasicInformation>  list = _SjDb.Queryable<HWEquipmentBasicInformation>()
           .Where(a => a.BID == input.BID).ToList();

        if (list.Count == 0) {

            throw Oops.Oh("任务不存在，驳回！");
        }

        
        else
        {
            //提交
            try
            {
                _SjDb.Ado.BeginTran();
                int count = await _SjDb.Updateable<HWEquipmentBasicInformation>()
                    .SetColumns(a => a.LIFECYCLE == 1)
                    .Where(a => a.BID == input.BID)
                    .ExecuteCommandAsync();


                int deleteCount = _SjDb.Deleteable<HWEquipmentBasicZi>().Where(it => it.DEVICENUMBER == list[0].DEVICENUMBER).ExecuteCommand();
                if (count != 1)
                {
                    throw Oops.Oh("删除失败！");
                }
                _SjDb.Ado.CommitTran();
                return "删除成功！";
            }
            catch (Exception e)
            {
                _SjDb.Ado.RollbackTran();
                throw Oops.Oh($"异常：{e.Message}");
            }
        }

    }


    /// <summary>
    /// 更改设备状态
    /// </summary>
    /// <returns></returns>
    [HttpPost("/HWYC/UpdateEquipmentState")]
    public async Task<string> UpdateEquipmentState(UpdateEquipmentStateInput input) {

        int selectCount = _SjDb.Queryable<HWEquipmentBasicInformation>()
                .Where(a => a.BID == input.BID)
                .Count();

        if (selectCount == 0)
        {
            throw Oops.Oh("任务不存在，驳回！");
        }
        else
        {
            //提交
            try
            {
                _SjDb.Ado.BeginTran();
                int count = await _SjDb.Updateable<HWEquipmentBasicInformation>()
                    .SetColumns(a => a.EQUIPMENTSTATE == input.EQUIPMENTSTATE)
                    .Where(a => a.BID == input.BID)
                    .ExecuteCommandAsync();

                if (count != 1)
                {
                    throw Oops.Oh("修改失败！");
                }
                _SjDb.Ado.CommitTran();
                return "修改成功！";
            }
            catch (Exception e)
            {
                _SjDb.Ado.RollbackTran();
                throw Oops.Oh($"异常：{e.Message}");
            }
        }




    }

    /// <summary>
    /// 更改设备信息
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost("/HWYC/UpdateEquipmentBasicInformation")]
    public async Task<string> UpdateEquipmentBasicInformation(UpdateEquipmentBasicInformationInput input)
    {

        if (input.MATERIALNO.Count == 0 || string.IsNullOrEmpty(input.EQUIPMENTTYPENO) || string.IsNullOrEmpty(input.DEVICENUMBER))
        {
            throw Oops.Oh($"请填写完整参数！");
        }
        DateTime dateTime = DateTime.Now;

        //判断单据存在
        int cnt = await _SjDb.Queryable<HWEquipmentBasicInformation>()
            .Where(a => a.DEVICENUMBER == input.DEVICENUMBER)
             .Where(l => l.LIFECYCLE == 0)
            .Select(a => a.BID)
            .CountAsync();
        if (cnt == 0)
        {
            throw Oops.Oh($"任务不存在！");
        }
        else
        {
            //提交
            try
            {
                _SjDb.Ado.BeginTran();
                int count = await _SjDb.Updateable<HWEquipmentBasicInformation>()
                     .SetColumns(a => a.EQUIPMENTTYPENO == input.EQUIPMENTTYPENO)
                     .SetColumns(a => a.DEVICENUMBER == input.DEVICENUMBER)
                      .SetColumns(a => a.MAINTENANCEINTERVALS == input.MAINTENANCEINTERVALS)
                     .Where(a => a.DEVICENUMBER == input.DEVICENUMBER)
                    .ExecuteCommandAsync();


              int deleteCount = _SjDb.Deleteable<HWEquipmentBasicZi>().Where(it => it.DEVICENUMBER == input.DEVICENUMBER).ExecuteCommand();

                List<HWEquipmentBasicZi> list = new List<HWEquipmentBasicZi>();
                foreach (MaterialnoMessage item in input.MATERIALNO)
                {
                    list.Add(new HWEquipmentBasicZi() {
                    MATERIALNO = item.MATERIALNO,
                    DEVICENUMBER = input.DEVICENUMBER,
                    ITEMNAME = item.ITEMNAME,
                    EQUIPMENTSPECS = item.EQUIPMENTSPECS,
                    CREATETIME = dateTime,


                    });


                }
                int cnt2 = await _SjDb.Insertable<HWEquipmentBasicZi>(list).ExecuteCommandAsync();

                if (count != 1 || cnt2==0)
                {
                    throw Oops.Oh("修改失败！");
                }
                _SjDb.Ado.CommitTran();
                return "修改成功！";
            }
            catch (Exception e)
            {
                _SjDb.Ado.RollbackTran();
                throw Oops.Oh($"异常：{e.Message}");
            }

        }

    }
} 
